package com.taotao.search.controller;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taotao.common.utils.ExceptionUtil;
import com.taotao.common.utils.TaotaoResult;
import com.taotao.search.pojo.SearchResult;
import com.taotao.search.service.SearchService;

@Controller
public class SearchController {

    private static Logger logger = LoggerFactory.getLogger(SearchController.class);

    @Autowired
    private SearchService searchService;

    /**
     * 接受查询参数 : 条件,page,rows 调用service执行查询, 返回结果
     */
    @RequestMapping(value = "/query", method = RequestMethod.GET, 
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8")
    @ResponseBody
    public TaotaoResult search(@RequestParam(value = "q") String queryString,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "60") Integer rows) {

        if (StringUtils.isBlank(queryString)) {
            return TaotaoResult.build(400, "查询条件不能为空");
        }
        try {
            queryString = new String(queryString.getBytes("iso8859-1"), "utf-8");
            SearchResult result = searchService.search(queryString, page, rows);
            return TaotaoResult.ok(result);
        } catch (Exception e) {
            logger.error("solr 查询出错", e);
            return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
        }
    }
}
